package com.learn.security.browser.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.learn.security.core.properties.enums.LoginType;
import com.learn.security.core.properties.SecurityProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录成功的处理
 * SavedRequestAwareAuthenticationSuccessHandler：spring security默认的登录成功处理器
 */
@Component
public class MyAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ObjectMapper objectMapper;

    // core包下管理可配置属性的对象
    @Autowired
    private SecurityProperties securityProperties;

    /**
     * 登录成功返回方式
     *      1.跳转（LoginType.REDIRECT）：返回页面（调用默认的登录成功处理器的onAuthenticationSuccess方法）
     *      2.json（LoginType.JSON）    ：返回json
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        logger.info("登录成功");

        if(LoginType.JSON.equals(securityProperties.getBrowser().getLoginType())){
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(objectMapper.writeValueAsString(authentication));
        }else {
            super.onAuthenticationSuccess(request,response,authentication);
        }

    }
}
